package com.aaamvc.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.aaamvc.util.ReflectUtil;
import com.aaamvc.util.StringUtil;
import com.aaamvc.xml.ActionBean;
import com.aaamvc.xml.ResultBean;
import com.aaamvc.xml.XmlParser;

/**
 * 核心控制器
 * @author Administrator
 *
 */
public class AAADispatcherServlet extends HttpServlet {


	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//1.解析请求的路径
		StringBuffer url= request.getRequestURL();
		String ctx = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+"/";
		
		//2.根据路径找到类和方法
		String actionName = StringUtil.getActionName(url.toString(), ctx);
		Map<String, ActionBean> beanmap = (Map<String, ActionBean>)this.getServletContext().getAttribute("actionMap");
		
		
		//3.执行相关方法，返回结果
		ResultBean resultBean = ReflectUtil.getResultBean(actionName, beanmap,request.getParameterMap(),request,response);
		
		//4.根据类型执行跳转还是转发
		if (resultBean != null && "redirect".equals(resultBean.getType())) {
			response.sendRedirect(ctx + resultBean.getPath());
		}else if (resultBean != null &&"dispather".equals(resultBean.getType())) {
			request.getRequestDispatcher(resultBean.getPath()).forward(request, response);
		}else {
			response.sendRedirect(ctx+"404.jsp");
		}
	
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
			this.doGet(request, response);
	}

	/**
	 * Initialization of the servlet. <br>
	 * 解析XML文件，放在application作用域
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		try {
			Map<String, ActionBean> map = XmlParser.getConfig();
			this.getServletContext().setAttribute("actionMap", map);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * Constructor of the object.
	 */
	public AAADispatcherServlet() {
		super();
	}

	public void destroy() {
		super.destroy(); 
	}


}
